package ynu;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Manager extends User{
    private String username;
    private static final String LOG_FILE = "D:\\java实训大作业\\日志文件.txt";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 场次计数器（每次程序启动时初始化）
    private static int showCounter = 0;

    public Manager(String username) {
        this.username = username;
        // 初始化场次计数器
        initializeShowCounter();
    }

    // 初始化场次计数器
    private void initializeShowCounter() {
        List<Show> shows = Show.readShows();
        if (!shows.isEmpty()) {
            // 找出最大的数字ID
            int maxId = 0;
            for (Show show : shows) {
                try {
                    // 尝试解析ID中的数字部分
                    String idStr = show.getId().replaceAll("\\D", "");
                    if (!idStr.isEmpty()) {
                        int idNum = Integer.parseInt(idStr);
                        if (idNum > maxId) {
                            maxId = idNum;
                        }
                    }
                } catch (NumberFormatException e) {
                    // 忽略格式不正确的ID
                }
            }
            showCounter = maxId;
        }
    }

    // 3. 影片管理菜单
    public void movieManagementMenu() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("\n===== 影片管理 =====");
            System.out.println("1. 列出所有正在上映影片");
            System.out.println("2. 添加影片信息");
            System.out.println("3. 修改影片信息");
            System.out.println("4. 删除影片信息");
            System.out.println("5. 查询影片信息");
            System.out.println("6. 返回上一级");
            System.out.print("请选择功能: ");

            int choice;
            try {
                choice = Integer.parseInt(scanner.nextLine());
                switch (choice) {
                    case 1:
                        listAllMovies();
                        break;
                    case 2:
                        addMovie();
                        break;
                    case 3:
                        modifyMovie();
                        break;
                    case 4:
                        deleteMovie();
                        break;
                    case 5:
                        queryMovies();
                        break;
                    case 6:
                        return;
                    default:
                        System.out.println("无效的选择，请重试！");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }
    }

    // 3.1 列出所有正在上映影片
    private void listAllMovies() {
        List<Movie> movies = Movie.readMovies();
        if (movies.isEmpty()) {
            System.out.println("当前没有上映的影片！");
            return;
        }

        System.out.println("\n===== 所有正在上映影片 =====");
        for (Movie movie : movies) {
            System.out.println("片名: " + movie.getName());
            System.out.println("导演: " + movie.getDirector());
            System.out.println("主演: " + movie.getActors());
            System.out.println("剧情简介: " + movie.getDescription());
            System.out.println("时长: " + movie.getDuration() + "分钟");
            System.out.println("评分: " + movie.getRating() + "/10分");
            System.out.println("------------------------");
        }
    }

    // 3.2 添加影片信息
    private void addMovie() {
        Scanner scanner = new Scanner(System.in);
        List<Movie> movies = Movie.readMovies();

        System.out.print("请输入影片名称: ");
        String name = scanner.nextLine();

        // 检查影片是否已存在
        if (Movie.findMovie(movies, name) != null) {
            System.out.println("该影片已存在！");
            return;
        }

        System.out.print("请输入导演: ");
        String director = scanner.nextLine();

        System.out.print("请输入主演: ");
        String actors = scanner.nextLine();

        System.out.print("请输入剧情简介: ");
        String description = scanner.nextLine();

        int duration = 0;
        while (true) {
            System.out.print("请输入时长(分钟): ");
            try {
                duration = Integer.parseInt(scanner.nextLine());
                if (duration > 0) break;
                System.out.println("时长必须为正数！");
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }

        double rating = -1;
        while (true) {
            System.out.print("请输入评分(0-10分): ");
            try {
                rating = Double.parseDouble(scanner.nextLine());
                if (rating >= 0 && rating <= 10) break;
                System.out.println("评分必须在0-10之间！");
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }

        movies.add(new Movie(name, director, actors, description, duration, rating));
        Movie.saveMovies(movies);
        System.out.println("影片添加成功！");
    }

    // 3.3 修改影片信息
    private void modifyMovie() {
        Scanner scanner = new Scanner(System.in);
        List<Movie> movies = Movie.readMovies();

        System.out.print("请输入要修改的影片名称: ");
        String name = scanner.nextLine();

        Movie movie = Movie.findMovie(movies, name);
        if (movie == null) {
            System.out.println("该影片不存在！");
            return;
        }

        System.out.print("请输入新的导演(原: " + movie.getDirector() + "): ");
        String director = scanner.nextLine();
        if (!director.isEmpty()) {
            movie.setDirector(director);
        }

        System.out.print("请输入新的主演(原: " + movie.getActors() + "): ");
        String actors = scanner.nextLine();
        if (!actors.isEmpty()) {
            movie.setActors(actors);
        }

        System.out.print("请输入新的剧情简介(原: " + movie.getDescription() + "): ");
        String description = scanner.nextLine();
        if (!description.isEmpty()) {
            movie.setDescription(description);
        }

        System.out.print("请输入新的时长(分钟，原: " + movie.getDuration() + "): ");
        String durationStr = scanner.nextLine();
        if (!durationStr.isEmpty()) {
            try {
                int duration = Integer.parseInt(durationStr);
                if (duration > 0) {
                    movie.setduration(duration);
                } else {
                    System.out.println("时长必须为正数，未修改！");
                }
            } catch (NumberFormatException e) {
                System.out.println("输入无效，时长未修改！");
            }
        }

        System.out.print("请输入新的评分(0-10分，原: " + movie.getRating() + "): ");
        String ratingStr = scanner.nextLine();
        if (!ratingStr.isEmpty()) {
            try {
                double rating = Double.parseDouble(ratingStr);
                if (rating >= 0 && rating <= 10) {
                    movie.setRating(rating);
                } else {
                    System.out.println("评分必须在0-10之间，未修改！");
                }
            } catch (NumberFormatException e) {
                System.out.println("输入无效，评分未修改！");
            }
        }

        Movie.saveMovies(movies);
        System.out.println("影片信息修改成功！");
    }

    // 3.4 删除影片信息
    private void deleteMovie() {
        Scanner scanner = new Scanner(System.in);
        List<Movie> movies = Movie.readMovies();

        System.out.print("请输入要删除的影片名称: ");
        String name = scanner.nextLine();

        Movie movie = Movie.findMovie(movies, name);
        if (movie == null) {
            System.out.println("该影片不存在！");
            return;
        }

        // 检查影片是否有排片
        List<Show> shows = Show.readShows();
        for (Show show : shows) {
            if (show.getMovieName().equals(name)) {
                System.out.println("该影片已有排片，无法删除！");
                return;
            }
        }

        System.out.print("确定要删除影片《" + name + "》吗？(y/n): ");
        String confirm = scanner.nextLine();
        if (confirm.equalsIgnoreCase("y")) {
            movies.remove(movie);
            Movie.saveMovies(movies);
            System.out.println("影片删除成功！");
        } else {
            System.out.println("已取消删除操作！");
        }
    }

    // 3.5 查询影片信息
    private void queryMovies() {
        Scanner scanner = new Scanner(System.in);
        List<Movie> movies = Movie.readMovies();

        System.out.println("1. 按片名查询");
        System.out.println("2. 按导演查询");
        System.out.println("3. 按主演查询");
        System.out.println("4. 组合查询");
        System.out.print("请选择查询方式: ");

        int choice;
        try {
            choice = Integer.parseInt(scanner.nextLine());
            List<Movie> result = new ArrayList<>();

            switch (choice) {
                case 1:
                    System.out.print("请输入片名: ");
                    String name = scanner.nextLine();
                    for (Movie movie : movies) {
                        if (movie.getName().contains(name)) {
                            result.add(movie);
                        }
                    }
                    break;
                case 2:
                    System.out.print("请输入导演: ");
                    String director = scanner.nextLine();
                    for (Movie movie : movies) {
                        if (movie.getDirector().contains(director)) {
                            result.add(movie);
                        }
                    }
                    break;
                case 3:
                    System.out.print("请输入主演: ");
                    String actor = scanner.nextLine();
                    for (Movie movie : movies) {
                        if (movie.getActors().contains(actor)) {
                            result.add(movie);
                        }
                    }
                    break;
                case 4:
                    System.out.print("请输入片名(可空): ");
                    String name2 = scanner.nextLine();
                    System.out.print("请输入导演(可空): ");
                    String director2 = scanner.nextLine();
                    System.out.print("请输入主演(可空): ");
                    String actor2 = scanner.nextLine();

                    for (Movie movie : movies) {
                        boolean match = true;
                        if (!name2.isEmpty() && !movie.getName().contains(name2)) match = false;
                        if (!director2.isEmpty() && !movie.getDirector().contains(director2)) match = false;
                        if (!actor2.isEmpty() && !movie.getActors().contains(actor2)) match = false;
                        if (match) result.add(movie);
                    }
                    break;
                default:
                    System.out.println("无效的选择！");
                    return;
            }

            // 显示查询结果
            if (result.isEmpty()) {
                System.out.println("没有找到匹配的影片！");
            } else {
                System.out.println("\n===== 查询结果 =====");
                for (Movie m : result) {
                    System.out.println("片名: " + m.getName());
                    System.out.println("导演: " + m.getDirector());
                    System.out.println("主演: " + m.getActors());
                    System.out.println("剧情简介: " + m.getDescription());
                    System.out.println("时长: " + m.getDuration() + "分钟");
                    System.out.println("评分: " + m.getRating() + "/10分");
                    System.out.println("------------------------");
                }
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字！");
        }
    }

    // 4. 排片管理菜单
    public void showManagementMenu() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("\n===== 排片管理 =====");
            System.out.println("1. 增加场次");
            System.out.println("2. 修改场次");
            System.out.println("3. 删除场次");
            System.out.println("4. 列出所有场次信息");
            System.out.println("5. 自动排片");
            System.out.println("6. 返回上一级");
            System.out.print("请选择功能: ");

            int choice;
            try {
                choice = Integer.parseInt(scanner.nextLine());
                switch (choice) {
                    case 1:
                        addShow();
                        break;
                    case 2:
                        modifyShow();
                        break;
                    case 3:
                        deleteShow();
                        break;
                    case 4:
                        listAllShows();
                        break;
                    case 5:
                        autoArrangeShows();
                        break;
                    case 6:
                        return;
                    default:
                        System.out.println("无效的选择，请重试！");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }
    }

    // 4.1 增加场次
    private void addShow() {
        Scanner scanner = new Scanner(System.in);
        List<Show> shows = Show.readShows();
        List<Movie> movies = Movie.readMovies();
        List<Theater> theaters = Theater.readTheaters();

        if (movies.isEmpty()) {
            System.out.println("没有影片可供排片，请先添加影片！");
            return;
        }

        // 显示所有影片供选择
        System.out.println("可供排片的影片:");
        for (int i = 0; i < movies.size(); i++) {
            System.out.println((i+1) + ". " + movies.get(i).getName());
        }
        System.out.print("请选择影片(输入序号): ");
        int movieIndex;
        try {
            movieIndex = Integer.parseInt(scanner.nextLine()) - 1;
            if (movieIndex < 0 || movieIndex >= movies.size()) {
                System.out.println("无效的选择！");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字！");
            return;
        }
        String movieName = movies.get(movieIndex).getName();

        // 显示所有放映厅供选择
        System.out.println("放映厅列表:");
        for (int i = 0; i < theaters.size(); i++) {
            Theater t = theaters.get(i);
            System.out.println((i+1) + ". " + t.getName() +
                    " (" + t.getRowCount() + "排，每排" +
                    t.getSeatCountPerRow() + "座)");
        }
        System.out.print("请选择放映厅(输入序号): ");
        int theaterIndex;
        try {
            theaterIndex = Integer.parseInt(scanner.nextLine()) - 1;
            if (theaterIndex < 0 || theaterIndex >= theaters.size()) {
                System.out.println("无效的选择！");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的极数字！");
            return;
        }
        Theater selectedTheater = theaters.get(theaterIndex);
        String theaterName = selectedTheater.getName();

        // 输入放映时间
        Date showTime = null;
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        while (true) {
            System.out.print("请输入放映时间(格式: yyyy-MM-dd HH:mm): ");
            String timeStr = scanner.nextLine();
            try {
                showTime = timeFormat.parse(timeStr);
                // 检查是否在一周内
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DAY_OF_YEAR, 7);
                if (showTime.after(cal.getTime())) {
                    System.out.println("只能排一周内的场次！");
                    continue;
                }
                // 检查该放映厅该时间是否已有排片
                boolean conflict = false;
                for (Show s : shows) {
                    if (s.getTheaterName().equals(theaterName) &&
                            Math.abs(s.getShowTime().getTime() - showTime.getTime()) < 3600000) {
                        // 两小时内视为冲突
                        conflict = true;
                        break;
                    }
                }
                if (conflict) {
                    System.out.println("该放映厅此时段已有排片，请选择其他时间！");
                    continue;
                }
                break;
            } catch (ParseException e) {
                System.out.println("时间格式错误，请重新输入！");
            }
        }

        // 输入票价
        double price = 0;
        while (true) {
            System.out.print("请输入票价: ");
            try {
                price = Double.parseDouble(scanner.nextLine());
                if (price > 0) break;
                System.out.println("票价必须为正数！");
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }

        // 生成简单ID: S + 递增数字
        showCounter++;
        String id = "S" + showCounter;

        // 添加场次（使用Theater对象）
        shows.add(new Show(id, movieName, theaterName, showTime, price, selectedTheater));
        Show.saveShows(shows);
        System.out.println("场次添加成功！ID: " + id);
    }


    // 4.2 修改场次
    private void modifyShow() {
        Scanner scanner = new Scanner(System.in);
        List<Show> shows = Show.readShows();
        List<Movie> movies = Movie.readMovies();
        List<Theater> theaters = Theater.readTheaters();

        if (shows.isEmpty()) {
            System.out.println("当前没有任何场次！");
            return;
        }

        // 显示所有场次供选择
        System.out.println("所有场次:");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (int i = 0; i < shows.size(); i++) {
            Show s = shows.get(i);
            System.out.println((i+1) + ". ID:" + s.getId() + " | " + s.getMovieName() + " - " +
                    s.getTheaterName() + " - " +
                    sdf.format(s.getShowTime()) + " - " + s.getPrice() + "元");
        }
        System.out.print("请选择要修改的场次(输入序号): ");
        int showIndex;
        try {
            showIndex = Integer.parseInt(scanner.nextLine()) - 1;
            if (showIndex < 0 || showIndex >= shows.size()) {
                System.out.println("无效的选择！");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字！");
            return;
        }
        Show show = shows.get(showIndex);

        // 检查是否有售出的票
        if (show.hasTicketsSold()) {
            System.out.println("该场次已有售票，无法修改！");
            return;
        }

        String oldMovieName = show.getMovieName();
        String oldTheaterName = show.getTheaterName();

        // 选择新影片
        System.out.println("可供选择的影片:");
        for (int i = 0; i < movies.size(); i++) {
            System.out.println((i+1) + ". " + movies.get(i).getName());
        }
        System.out.print("请选择新影片(输入序号，按回车保持不变): ");
        String movieChoice = scanner.nextLine();
        if (!movieChoice.isEmpty()) {
            try {
                int movieIndex = Integer.parseInt(movieChoice) - 1;
                if (movieIndex >= 0 && movieIndex < movies.size()) {
                    show.setMovieName(movies.get(movieIndex).getName());
                } else {
                    System.out.println("无效的选择，影片未修改！");
                }
            } catch (NumberFormatException e) {
                System.out.println("输入无效，影片未修改！");
            }
        }

        // 选择新放映厅
        System.out.println("放映厅列表:");
        for (int i = 0; i < theaters.size(); i++) {
            System.out.println((i+1) + ". " + theaters.get(i).getName());
        }
        System.out.print("请选择新放映厅(输入序号，按回车保持不变): ");
        String theaterChoice = scanner.nextLine();
        if (!theaterChoice.isEmpty()) {
            try {
                int theaterIndex = Integer.parseInt(theaterChoice) - 1;
                if (theaterIndex >= 0 && theaterIndex < theaters.size()) {
                    Theater newTheater = theaters.get(theaterIndex);
                    show.setTheaterName(newTheater.getName());

                    // 更换放映厅时重置座位状态
                    show.setSeatMap(newTheater.initSeatMap());
                } else {
                    System.out.println("无效的选择，放映厅未修改！");
                }
            } catch (NumberFormatException e) {
                System.out.println("输入无效，放映厅未修改！");
            }
        }

        // 修改放映时间
        System.out.print("请输入新的放映时间(格式: yyyy-MM-dd HH:mm，按回车保持不变): ");
        String timeStr = scanner.nextLine();
        if (!timeStr.isEmpty()) {
            try {
                Date newTime = sdf.parse(timeStr);
                // 检查是否在一周内
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DAY_OF_YEAR, 7);
                if (newTime.after(cal.getTime())) {
                    System.out.println("只能排一周内的场次，时间未修改！");
                } else {
                    // 检查该放映厅该时间是否已有排片
                    boolean conflict = false;
                    for (int i = 0; i < shows.size(); i++) {
                        if (i != showIndex &&
                                shows.get(i).getTheaterName().equals(show.getTheaterName()) &&
                                Math.abs(shows.get(i).getShowTime().getTime() - newTime.getTime()) < 3600000) {
                            conflict = true;
                            break;
                        }
                    }
                    if (conflict) {
                        System.out.println("该放映厅此时段已有排片，时间未修改！");
                    } else {
                        show.setShowTime(newTime);
                    }
                }
            } catch (ParseException e) {
                System.out.println("时间格式错误，时间未修改！");
            }
        }

        // 修改票价
        System.out.print("请输入新的票价(按回车保持不变): ");
        String priceStr = scanner.nextLine();
        if (!priceStr.isEmpty()) {
            try {
                double newPrice = Double.parseDouble(priceStr);
                if (newPrice > 0) {
                    show.setPrice(newPrice);
                } else {
                    System.out.println("票价必须为正数，票价未修改！");
                }
            } catch (NumberFormatException e) {
                System.out.println("输入无效，票价未修改！");
            }
        }

        Show.saveShows(shows);
        System.out.println("场次修改成功！");
        logOperation("修改场次信息: ID " + show.getId() +
                " 原片名 " + oldMovieName + " 修改后片名 " + show.getMovieName() +
                " 原放映厅 " + oldTheaterName + " 新放映厅 " + show.getTheaterName());
    }

    // 4.3 删除场次
    private void deleteShow() {
        Scanner scanner = new Scanner(System.in);
        List<Show> shows = Show.readShows();

        if (shows.isEmpty()) {
            System.out.println("当前没有任何场次！");
            return;
        }

        // 显示所有场次供选择
        System.out.println("所有场次:");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (int i = 0; i < shows.size(); i++) {
            Show s = shows.get(i);
            System.out.println((i+1) + ". ID:" + s.getId() + " | " + s.getMovieName() + " - " +
                    s.getTheaterName() + " - " +
                    sdf.format(s.getShowTime()) + " - " + s.getPrice() + "元");
        }
        System.out.print("请选择要删除的场次(输入序号): ");
        int showIndex;
        try {
            showIndex = Integer.parseInt(scanner.nextLine()) - 1;
            if (showIndex < 0 || showIndex >= shows.size()) {
                System.out.println("无效的选择！");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字！");
            return;
        }
        Show show = shows.get(showIndex);

        // 检查是否有售出的票
        if (show.hasTicketsSold()) {
            System.out.println("该场次已有售票，无法删除！");
            return;
        }

        System.out.print("确定要删除该场次吗？(y/n): ");
        String confirm = scanner.nextLine();
        if (confirm.equalsIgnoreCase("y")) {
            String showId = show.getId();
            shows.remove(showIndex);
            Show.saveShows(shows);
            System.out.println("场次删除成功！");
            logOperation("删除场次信息: ID " + showId);
        } else {
            System.out.println("已取消删除操作！");
        }
    }

    // 4.4 列出所有场次信息
    private void listAllShows() {
        Scanner scanner = new Scanner(System.in);
        List<Show> shows = Show.readShows();

        if (shows.isEmpty()) {
            System.out.println("当前没有任何场次！");
            return;
        }

        System.out.println("1. 最近一周场次");
        System.out.println("2. 当日场次");
        System.out.println("3. 近3日场次");
        System.out.print("请选择查看范围: ");

        int choice;
        try {
            choice = Integer.parseInt(scanner.nextLine());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Calendar cal = Calendar.getInstance();
            Date now = new Date();
            List<Show> filteredShows = new ArrayList<>();

            switch (choice) {
                case 1:
                    // 最近一周
                    cal.add(Calendar.DAY_OF_YEAR, 7);
                    Date oneWeekLater = cal.getTime();
                    for (Show s : shows) {
                        if (s.getShowTime().after(now) && s.getShowTime().before(oneWeekLater)) {
                            filteredShows.add(s);
                        }
                    }
                    break;
                case 2:
                    // 当日
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                    cal.set(Calendar.MINUTE, 0);
                    cal.set(Calendar.SECOND, 0);
                    Date todayStart = cal.getTime();
                    cal.add(Calendar.DAY_OF_YEAR, 1);
                    Date tomorrowStart = cal.getTime();

                    for (Show s : shows) {
                        if (s.getShowTime().after(todayStart) && s.getShowTime().before(tomorrowStart)) {
                            filteredShows.add(s);
                        }
                    }
                    break;
                case 3:
                    // 近3日
                    cal.add(Calendar.DAY_OF_YEAR, 3);
                    Date threeDaysLater = cal.getTime();
                    for (Show s : shows) {
                        if (s.getShowTime().after(now) && s.getShowTime().before(threeDaysLater)) {
                            filteredShows.add(s);
                        }
                    }
                    break;
                default:
                    System.out.println("无效的选择！");
                    return;
            }

            // 按时间排序
            filteredShows.sort(Comparator.comparing(Show::getShowTime));

            // 显示结果
            if (filteredShows.isEmpty()) {
                System.out.println("该范围内没有场次！");
            } else {
                System.out.println("\n===== 场次列表 =====");
                for (Show s : filteredShows) {
                    System.out.println("ID: " + s.getId());
                    System.out.println("影片: " + s.getMovieName());
                    System.out.println("放映厅: " + s.getTheaterName());
                    System.out.println("时间: " + sdf.format(s.getShowTime()));
                    System.out.println("票价: " + s.getPrice() + "元");

                    // 计算座位状态（使用二维数组）
                    char[][] seatMap = s.getSeatMap();
                    int totalSeats = s.getRows() * s.getCols();
                    int soldSeats = 0;
                    for (char[] row : seatMap) {
                        for (char seat : row) {
                            if (seat == 'X') soldSeats++;
                        }
                    }
                    System.out.println("座位状态: " + soldSeats + "/" + totalSeats + "已售");
                    System.out.println("------------------------");
                }
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字！");
        }
    }

    // 4.5 自动排片功能
    private void autoArrangeShows() {
        List<Movie> movies = Movie.readMovies();
        List<Theater> theaters = Theater.readTheaters();
        List<Show> shows = Show.readShows();

        if (movies.isEmpty()) {
            System.out.println("没有影片可供排片，请先添加影片！");
            return;
        }

        // 按评分排序，高分影片优先排片
        movies.sort((m1, m2) -> Double.compare(m2.getRating(), m1.getRating()));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar cal = Calendar.getInstance();

        // 获取当前自动排片ID起始值
        int autoIdCounter = getAutoShowIdCounter(shows);

        // 安排未来7天的场次
        for (int day = 0; day < 7; day++) {
            // 设置日期
            cal.setTime(new Date());
            cal.add(Calendar.DAY_OF_YEAR, day);

            // 黄金时段（19:00-21:00）安排高分影片
            cal.set(Calendar.HOUR_OF_DAY, 19);
            cal.set(Calendar.MINUTE, 0);
            autoIdCounter = arrangeShowForTime(cal.getTime(), movies, 0, theaters, shows, autoIdCounter);

            // 其他时段安排其他影片
            cal.set(Calendar.HOUR_OF_DAY, 10);
            cal.set(Calendar.MINUTE, 0);
            autoIdCounter = arrangeShowForTime(cal.getTime(), movies, 1, theaters, shows, autoIdCounter);

            cal.set(Calendar.HOUR_OF_DAY, 14);
            cal.set(Calendar.MINUTE, 0);
            autoIdCounter = arrangeShowForTime(cal.getTime(), movies, 2, theaters, shows, autoIdCounter);

            cal.set(Calendar.HOUR_OF_DAY, 16);
            cal.set(Calendar.MINUTE, 0);
            autoIdCounter = arrangeShowForTime(cal.getTime(), movies, 3, theaters, shows, autoIdCounter);
        }

        Show.saveShows(shows);
        System.out.println("自动排片完成！");
    }

    // 为特定时间安排场次
    private int arrangeShowForTime(Date time, List<Movie> movies, int movieIndex,
                                   List<Theater> theaters, List<Show> shows, int autoIdCounter) {
        // 检查时间是否在当前时间之后
        if (time.before(new Date())) {
            return autoIdCounter;
        }

        // 选择影片（循环使用影片列表）
        int index = movieIndex % movies.size();
        String movieName = movies.get(index).getName();

        // 为每个放映厅安排场次
        for (Theater theater : theaters) {
            // 检查该放映厅该时间是否已有排片
            boolean conflict = false;
            for (Show s : shows) {
                if (s.getTheaterName().equals(theater.getName()) &&
                        Math.abs(s.getShowTime().getTime() - time.getTime()) < 1800000) { // 30分钟内视为冲突
                    conflict = true;
                    break;
                }
            }

            if (!conflict) {
                // 根据放映厅级别设置不同票价
                double price = 50; // 默认票价
                if (theater.getName().contains("黄金")) price = 80;
                else if (theater.getName().contains("白银")) price = 70;
                else if (theater.getName().contains("钻石")) price = 75;

                // 生成简单ID: A + 递增数字
                autoIdCounter++;
                String id = "A" + autoIdCounter;

                // 添加场次（使用Theater对象）
                shows.add(new Show(id, movieName, theater.getName(), time, price, theater));
            }

            // 切换到下一部影片
            index = (index + 1) % movies.size();
            movieName = movies.get(index).getName();
        }

        return autoIdCounter;
    }

    // 获取当前自动排片ID计数器
    private int getAutoShowIdCounter(List<Show> shows) {
        int maxId = 0;
        for (Show show : shows) {
            if (show.getId().startsWith("A")) {
                try {
                    // 提取数字部分
                    String numPart = show.getId().substring(1);
                    int idNum = Integer.parseInt(numPart);
                    if (idNum > maxId) {
                        maxId = idNum;
                    }
                } catch (NumberFormatException e) {
                    // 忽略格式不正确的ID
                }
            }
        }
        return maxId;
    }

    // 5. 查看销售数据菜单
    public void viewSalesDataMenu() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("\n===== 查看销售数据 =====");
            System.out.println("1. 查看当日销售数据");
            System.out.println("2. 查看当周销售数据");
            System.out.println("3. 查看当月销售数据");
            System.out.println("4. 返回上一级");
            System.out.print("请选择功能: ");

            int choice;
            try {
                choice = Integer.parseInt(scanner.nextLine());
                switch (choice) {
                    case 1:
                        viewDailySalesData();
                        break;
                    case 2:
                        viewWeeklySalesData();
                        break;
                    case 3:
                        viewMonthlySalesData();
                        break;
                    case 4:
                        return;
                    default:
                        System.out.println("无效的选择，请重试！");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }
    }

    // 5.1 查看当日销售数据
    private void viewDailySalesData() {
        List<SaleData> sales = SaleData.readSaleData();
        if (sales.isEmpty()) {
            System.out.println("没有销售数据！");
            return;
        }

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Date todayStart = cal.getTime();

        cal.add(Calendar.DAY_OF_YEAR, 1);
        Date tomorrowStart = cal.getTime();

        // 筛选当日数据
        List<SaleData> dailySales = new ArrayList<>();
        for (SaleData sale : sales) {
            if (!sale.isRefunded() && sale.getSaleTime().after(todayStart) &&
                    sale.getSaleTime().before(tomorrowStart)) {
                dailySales.add(sale);
            }
        }

        if (dailySales.isEmpty()) {
            System.out.println("今日没有销售数据！");
            return;
        }

        // 统计数据
        double totalSales = 0;
        int totalTickets = 0;
        int refundedTickets = 0;
        double refundedAmount = 0;

        // 按场次统计
        Map<String, Integer> showTicketCount = new HashMap<>();
        Map<String, Double> showSalesAmount = new HashMap<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (SaleData sale : sales) {
            if (sale.getSaleTime().after(todayStart) && sale.getSaleTime().before(tomorrowStart)) {
                String showKey = sale.getMovieName() + "|" + sale.getTheaterName() + "|" +
                        sdf.format(sale.getShowTime());

                if (sale.isRefunded()) {
                    refundedTickets++;
                    refundedAmount += sale.getPrice();
                } else {
                    totalTickets++;
                    totalSales += sale.getPrice();

                    showTicketCount.put(showKey, showTicketCount.getOrDefault(showKey, 0) + 1);
                    showSalesAmount.put(showKey, showSalesAmount.getOrDefault(showKey, 0.0) + sale.getPrice());
                }
            }
        }

        // 显示统计结果
        System.out.println("\n===== 当日销售数据 =====");
        System.out.println("日期: " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        System.out.println("总售票数: " + totalTickets);
        System.out.println("总销售额: " + totalSales + "元");
        System.out.println("退票数: " + refundedTickets);
        System.out.println("退票金额: " + refundedAmount + "元");
        System.out.println("\n各场次销售情况:");

        for (String key : showTicketCount.keySet()) {
            String[] parts = key.split("\\|");
            System.out.println("影片: " + parts[0]);
            System.out.println("放映厅: " + parts[1]);
            System.out.println("时间: " + parts[2]);
            System.out.println("售票数: " + showTicketCount.get(key));
            System.out.println("销售额: " + showSalesAmount.get(key) + "元");
            System.out.println("------------------------");
        }
    }

    // 5.2 查看当周销售数据
    private void viewWeeklySalesData() {
        List<SaleData> sales = SaleData.readSaleData();
        if (sales.isEmpty()) {
            System.out.println("没有销售数据！");
            return;
        }

        Calendar cal = Calendar.getInstance();
        // 设置为本周日凌晨
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        // 如果当前是周日，减去一周
        if (cal.getTime().after(new Date())) {
            cal.add(Calendar.WEEK_OF_YEAR, -1);
        }
        Date weekStart = cal.getTime();

        cal.add(Calendar.WEEK_OF_YEAR, 1);
        Date weekEnd = cal.getTime();

        // 统计数据
        double totalSales = 0;
        int totalTickets = 0;
        int refundedTickets = 0;
        double refundedAmount = 0;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (SaleData sale : sales) {
            if (sale.getSaleTime().after(weekStart) && sale.getSaleTime().before(weekEnd)) {
                if (sale.isRefunded()) {
                    refundedTickets++;
                    refundedAmount += sale.getPrice();
                } else {
                    totalTickets++;
                    totalSales += sale.getPrice();
                }
            }
        }

        // 显示统计结果
        System.out.println("\n===== 当周销售数据 =====");
        System.out.println("时间段: " + sdf.format(weekStart) + " 至 " + sdf.format(weekEnd));
        System.out.println("总售票数: " + totalTickets);
        System.out.println("总销售额: " + totalSales + "元");
        System.out.println("退票数: " + refundedTickets);
        System.out.println("退票金额: " + refundedAmount + "元");
    }

    // 5.3 查看当月销售数据
    private void viewMonthlySalesData() {
        List<SaleData> sales = SaleData.readSaleData();
        if (sales.isEmpty()) {
            System.out.println("没有销售数据！");
            return;
        }

        Calendar cal = Calendar.getInstance();
        // 设置为本月第一天凌晨
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Date monthStart = cal.getTime();

        // 设置为下月第一天凌晨
        cal.add(Calendar.MONTH, 1);
        Date monthEnd = cal.getTime();

        // 统计数据
        double totalSales = 0;
        int totalTickets = 0;
        int refundedTickets = 0;
        double refundedAmount = 0;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        for (SaleData sale : sales) {
            if (sale.getSaleTime().after(monthStart) && sale.getSaleTime().before(monthEnd)) {
                if (sale.isRefunded()) {
                    refundedTickets++;
                    refundedAmount += sale.getPrice();
                } else {
                    totalTickets++;
                    totalSales += sale.getPrice();
                }
            }
        }

        // 显示统计结果
        System.out.println("\n===== 当月销售数据 =====");
        System.out.println("月份: " + sdf.format(new Date()));
        System.out.println("总售票数: " + totalTickets);
        System.out.println("总销售额: " + totalSales + "元");
        System.out.println("退票数: " + refundedTickets);
        System.out.println("退票金额: " + refundedAmount + "元");
    }

    // 记录日志
    private void logOperation(String operation) {
        File dir = new File("D:\\java实训大作业");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try (BufferedWriter bw = new BufferedWriter(new FileWriter(LOG_FILE, true))) {
            String log = "[" + sdf.format(new Date()) + "] " +
                    "操作类型: " + operation + " 操作人: " + username;
            bw.write(log);
            bw.newLine();
        } catch (IOException e) {
            System.out.println("记录日志出错: " + e.getMessage());
        }
    }
}
